/*本模块功能:选课申请
        编写者:朱光曜
        编写时间:2017.10.30*/
$(function() {
    var loading1 = new Loading();//监控全局ajax添加loading

    loading1.init();
    $(document).ajaxSend(function(){
        loading1.show();

    });
    $(document).ajaxStop(function(){
        loading1.hide();

    });
    //document.addEventListener('DOMSubtreeModified',function(e){//去除空格
    $(".className").attr("maxlength","20");


    $(".branch").attr("maxlength","6");
    $.map($(".className"),function (opt) {//长度限制
        maxLengthLimit.init(opt);
    });
    $.map($(".branch"),function (opt) {//长度限制
        maxLengthLimit.init(opt);
    });

    //});
    var string1 = '<tr>' +
        '<th class="col-lg-2">序号</th>' +
        '<th class="col-lg-6">院系名称</th>' +
        '<th class="col-lg-5">课程名称</th>' +
        '<th class="col-lg-2">学分</th>' +
        '<th class="col-lg-3">人数</th>' +
        '<th class="col-lg-3">状态</th>' +
        '<th class="col-lg-4">操作</th>' +
        '</tr>';
    //列表头部
    var box1 = new  Confirm;
    var box = new  Alert;
    function tabelModel(data) {//列表内容
        if(!data.selectList[key].selectMark) {
            var selects = "选择";
            var apply="未申请";
        } else {
            var selects = "退选";
            var apply="已申请";
        }
        var stuNums=data.selectList[key].stuNum;
        if(!stuNums){
            stuNums=0;
        }
        return '<tr data-num="0" courseId="' + data.selectList[key].courseId + '" stuorteaId="' + data.selectList[key].teacherId + '" >' +
            '<td class="col-lg-2" >' + (parseInt(key)+1) + '</td>' +
            '<td class="col-lg-6"  title="' + data.selectList[key].departmentName + '">' + data.selectList[key].departmentName + '</td>' +
            '<td class="col-lg-5"  title="' + data.selectList[key].courseName + '"  >' + data.selectList[key].courseName + '</td>' +
            '<td class="col-lg-2">' + data.selectList[key].courseCredit + '</td>' +
            '<td class="col-lg-3">(' + stuNums + '/' + data.selectList[key].maxStu + ')</td>' +
            '<td class="col-lg-3">'+ apply + '</td>' +
            '<td class="col-lg-4 last">' +
            '<a href="javascript:;" class="repairBtn">简介</a>' +
            '<a class="specialBtn" href="javascript:;">' + selects + '</a>' +
            '</td>' +
            '</tr>';

    }
    var nowData = 1;
    var index = {

        init: function() {
            this.bind();
        },
        bind: function() {
            var self = this;
            this.data_content = {}; //搜索集
            this.tab_content = {}; //列表集
            this.parameter = {
                "pageNow": 1,
                "pageSize": 10
            };

            this.postData(this.parameter, nowData);
            $(".form-control").bind('input propertychange',function(){

                var regy = /\s/g;
                if(regy.test($(this).val())){
                    $(this).val($(this).val().replace(/\s|\xA0/g,"")) ;
                }
            });
            $(document).off("click", ".tableBox td.last .repairBtn").on("click", ".tableBox td.last .repairBtn", function() { //简介点击
                var courseId = $(this).parents("tr").attr("courseId");
                var stuorteaId = $(this).parents("tr").attr("stuorteaId");

                self.summary(Number(courseId), stuorteaId);

            });

            $(document).off("click", ".tableBox td.last .specialBtn").on("click", ".tableBox td.last .specialBtn", function() { //选择点击
                var courseId = $(this).parents("tr").attr("courseId");
                if($(this).html() == "退选") {
                    self.elected(courseId);
                }
                if($(this).html() == "选择") {
                    self.choice(courseId);
                }
            });
        },
        add: function() { //搜索追加
            var self = this;
            var data = self.data_content;
            for(key in data.departmentList) {
                $(".mainContent .funBox .publicSelect").eq(0).append("<option departmentId=" + data.departmentList[key].departmentId + ">" + data.departmentList[key].departmentName + "</option>");
            }
            /*for(key in data.directList) {
                $(".mainContent .funBox .publicSelect").eq(2).append("<option value=" + data.directList[key].mainId + ">" + data.directList[key].directName + "</option>");
            }
            for(key in data.professionList) {
                $(".mainContent .funBox .publicSelect").eq(1).append("<option value=" + data.professionList[key].professionId + ">" + data.professionList[key].professionName + "</option>");
            }
            for(key in data.userList) {
                $(".mainContent .funBox .publicSelect").eq(3).append("<option value=" + data.userList[key].stuorteaId + ">" + data.userList[key].userName + "</option>");
            }*/
            $("#commencementDepartment").on("change", function() {//院系联动专业
                if($("#commencementDepartment option:selected").attr("departmentId") == null) {

                    $("#major").html('<option value="1" >请选择</option>');
                } else {

                    var parameter = {
                        "departmentId": $("#commencementDepartment option:selected").attr("departmentId")
                    };

                    $.ajax({
                        type: "post",
                        url: "getProfessionListByDepmentId",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(parameter)
                        },
                        success: function(data) {
                            //获取地点

                            var msgNew = JSON.parse(data);
                            var con = "<option>请选择</option>";

                            for(key in msgNew.professionList) {
                                con += '<option value="1" professionId="' + msgNew.professionList[key].professionId + '">' + msgNew.professionList[key].professionName + '</option>';
                            }
                            $("#major").html(con);

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                }
            });
            $("#major").on("change", function() {//专业联动方向
                if($("#major option:selected").attr("professionId") == null) {

                    $("#majorDirection").html('<option value="1" >请选择</option>');
                } else {

                    var parameter = {
                        "professionId": $("#major option:selected").attr("professionId")
                    };
//					for(i in parameter){//遍历转换数字格式
//						if(!isNaN(parameter[i])){
//							parameter[i]=Number(parameter[i]);
//						}
//					}


                    $.ajax({
                        type: "post",
                        url: "getMyProCourseList",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(parameter)
                        },
                        success: function(data) {
                            //获取地点

                            var msgNew = JSON.parse(data);
                            var con = "<option>请选择</option>";

                            for(key in msgNew.directList) {
                                con += '<option value="1" mainId="' + msgNew.directList[key].mainId + '">' + msgNew.directList[key].directName + '</option>';
                            }
                            $("#majorDirection").html(con);

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                }
            });
            $("#major").on("change", function() {//专业联动教师
                if($("#major option:selected").attr("professionId") == null) {

                    $("#teacher").html('<option value="1" >请选择</option>');
                } else {

                    var parameter = {
                        "departmentId": $("#major option:selected").attr("professionId")
                    };

                    $.ajax({
                        type: "post",
                        url: "getMyProCourseList",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(parameter)
                        },
                        success: function(data) {
                            //获取地点

                            var msgNew = JSON.parse(data);
                            var con = "<option>请选择</option>";

                            for(key in msgNew.teacherListAll) {
                                con += '<option value="1" stuorteaId="' + msgNew.teacherListAll[key].stuorteaId + '">' + msgNew.teacherListAll[key].userName + '</option>';
                            }
                            $("#teacher").html(con);

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                }
            });
            $(".funBox .searchBtn").off("click").click(function() { //搜索点击
                var courseCredit = $(".mainContent .form2 .branch").val();
                var n = /^[1-9]\d*$|^0$/;
                if(!n.test(courseCredit)&&courseCredit.length!==0) {

                    self.alert2("请输入数字信息");
                    return false;
                }
                var courseName = $(".mainContent .form2 .className").val();
                if(verification.specialCode(courseName) !== true) {
                    self.alert2("不能输入特殊字符(@/'\"#$%&^*)");
                    return false;
                }
                var departmentId = $('#commencementDepartment option:selected').attr("departmentId");
                var professionId = $('#major  option:selected').attr("professionId");
                var mainId = $('#majorDirection   option:selected').attr("mainId");
                var stuorteaId = $('#teacher  option:selected').attr("stuorteaId");
                var nowData = 1;
                var parameter = {
                    "courseName": courseName,
                    "courseCredit": courseCredit,

                    "departmentId": departmentId,
                    "professionId": professionId,
                    "mainId": mainId,
                    "stuorteaId": stuorteaId,
                    "pageNow": 1,
                    "pageSize": 10
                };
                var j=0;
                //遍历删除空元素
                for(i in parameter){
                    if(j<2){j++;continue;}
                    if(parameter[i]==null||parameter[i]==""){
                        delete parameter[i];
                    }
                    if(!isNaN(parameter[i])){
                        parameter[i]=Number(parameter[i]);
                    }
                }



                self.postData(parameter, nowData,1);
            });

        },
        tab_add: function() { //列表追加
            var self = this;
            var data = self.tab_content;
            var table=string1;

            //data.selectList={};


            var i = 0;
            for(key in data.selectList) {
                i++;
            }

            if(i > 0) {


                for(key in data.selectList) {

                    table += tabelModel(data);
                }


                $(".mainContent .tableBox").html(table);
            } else {
                var trImg = "<tr><td colspan='7'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td/tr>";
                $(".mainContent .tableBox").html(string1+ trImg);
            }
            //设置列表宽度(最大为9)
            var numMax = 0;
            $(".tableBox tr th").each(function() {
                var str = $(this).attr("class");
                var num = str.lastIndexOf("col-lg-") + 7;
                var num1 = parseFloat(str.substring(num, num + 1));
                numMax += num1;
            });

            $(".tableBox tr th").each(function() {
                var str = $(this).attr("class");
                var num = str.lastIndexOf("col-lg-") + 7;
                var num1 = parseFloat(str.substring(num, num + 1));

                $(this).css("width", num1 / numMax * 100 + "%");
            });
        },
        postData: function(par_data, nowData,hunt) { //获得搜索及列表数据
            var self = this;
            var parameter = par_data;

            $.ajax({
                type: "post",
                url: "skipStuSelectCoursesList",
                async: true,
                data:{
                    "jsonStr":	JSON.stringify(parameter)
                },
                success: function(data, status, xhr) {
                    var new_data = JSON.parse(data);

                    if(hunt) {
                        self.tab_content = new_data;

                        self.tab_add();
                    } else {

                        self.data_content = new_data;
                        self.tab_content = new_data;

                        self.add();
                        self.tab_add();
                    }
                    // console.log(new_data.totalPage+"啊啊"+new_data.pageNow)
                    var sumpage = new_data.totalPage;

                    if(sumpage<1){sumpage=1;};
                    var nowpage = 1;
                    var pagenumber = 10;
                    var parame = parameter;
                    $(".tcdPageCode").createPage({
                        pageCount: sumpage, //总页数
                        current: nowpage, //当前页数
                        pageNumber: pagenumber, //每页显示数量
                        backFn: function(p) {

                            nowpage = p;

                            if(nowpage >= sumpage) {
                                nowpage = sumpage;
                            }
                            if(!parameter) {
                                parameter = {
                                    "pageNow": nowpage,
                                    "pageSize": 10
                                };

                            } else {
                                parameter.pageNow = nowpage;

                            }
                            $.ajax({
                                type: "post",
                                url: "skipStuSelectCoursesList",
                                async: true,
                                data:{
                                    "jsonStr":	JSON.stringify(parameter)
                                },
                                async: true,
                                success: function(msg) {
                                    //获取院系
                                    var msgNew= JSON.parse(msg);
                                    self.tab_content = msgNew;

                                    self.tab_add();
                                },
                                error: function(data, status, xhr) {
                                    var json = JSON.stringify({
                                        "pageName": "error"
                                    });
                                    window.location.href = "skipPage?jsonStr=" + json;

                                }
                            });
                        }
                    });
                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        alert1: function(content1, method) { //confirm提示

            box1.contenthead = "提示";
            box1.content = content1;
            if(method) {
                box1.success = method;
            }

            box1.init();
            box1.show();
        },
        alert2: function(content2, method) { //alert提示

            box.contenthead = "提示";
            box.content = content2;
            if(method) {
                box.success = method;
            }
            box.init();
            box.show();
        },
        choice: function(courseId) { //选课申请
            var self = this;

            var content = "你确定选定这门课程么?";
            var courseI={"courseId": parseInt(courseId)};

            var method = function() { //success为提交成功后执行的方法
                $.ajax({
                    type: "post",
                    url: "stuSelectCourse",
                    async: true,

                    data:{
                        "jsonStr":	JSON.stringify(courseI)
                    },
                    success: function(data, status, xhr) {

                        var data=JSON.parse(data);
                        var method=function(){
                            window.location.reload();
                        };
                        if(data.result == "success") {
                            self.alert2("选择成功",method);

                        } else if(data.failMsg) {
                            self.alert2(data.failMsg);
                            return;
                        } else {
                            self.alert2("提交失败");

                        }

                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;

                    }
                });
            };
            self.alert1(content, method);

        },
        elected: function(courseId) { //推选申请
            var self = this;
            var courseI={"courseId": parseInt(courseId)};

            var content = "你确定退选这门课程么?";
            var method = function() { //success为提交成功后执行的方法
                $.ajax({
                    type: "post",
                    url: "stuReturnCourse",
                    async: true,

                    data: {
                        "jsonStr": JSON.stringify(courseI)
                    },
                    success: function(data, status, xhr) {

                        var data=JSON.parse(data);

                        var method=function(){
                            window.location.reload();
                        };
                        if(data.result == "success") {
                            self.alert2("退选成功",method);

                        } else if(data.result == "fail") {
                            self.alert2(data.failMsg,method);
                        } else {
                            self.alert2("提交失败",method);

                        }

                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;
                    }
                });
            };
            self.alert1(content, method);
        },
        summary: function(courseId, stuorteaId) { //简介弹窗
            var self = this;
            var boxSum = new  Alert;
            boxSum.contenthead = "课程简介";
            var courseI={"courseId": courseId,"stuorteaId": stuorteaId};

            $.ajax({
                type: "post",
                url: "getIntroctionByIds",
                async: true,

                data:{
                    "jsonStr":	JSON.stringify(courseI)
                },
                success: function(data, status, xhr) {
                    var new_data = JSON.parse(data);

                    boxSum.content = '<ul id="summary"><li><span>教师简介:&ensp;</span><span>' + new_data.userContect + '</span></li><div class="clear"></div><li><span>课程简介:&ensp;</span><span>' + new_data.courseIntroduction + '</span></li></ul><div class="clear"></div>';
                    boxSum.success=function(){
                        $(".alert_content").css({
                            "padding": "50px 10px 20px"
                        });

                    };
                    boxSum.init();
                    $(".alert_box" ).css({
                        "width": "586px",
                        "height": "358px"
                    }).children(".alert_content").css({
                        "padding-bottom": 0,
                        "padding-top": "5px"
                    });
                    $(".alert_contenthead" ).css({
                        "font-size": "18px"
                    });
                    $(".alert_content" ).css({
                        "height": "auto",
                        "min-height": "34px"
                    });
                    boxSum.show();

                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });

        }

    };

    index.init();

});